package com.irdstudio.tdp.console.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.irdstudio.sdk.beans.core.vo.EasyUITreeData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.irdstudio.tdp.console.service.facade.AppModelTreeService;
import com.irdstudio.tdp.console.dao.AppModelTreeDao;
import com.irdstudio.tdp.console.dao.domain.AppModelTree;
import com.irdstudio.tdp.console.service.vo.AppModelTreeVO;
import com.irdstudio.sdk.beans.core.base.FrameworkService;
/**
 * <p>ServiceImpl: 应用模型结构树				<p>
 * @author zjj
 * @date 2021-03-16
 */
@Service("appModelTreeServiceImpl")
public class AppModelTreeServiceImpl implements AppModelTreeService, FrameworkService {
	
	private static Logger logger = LoggerFactory.getLogger(AppModelTreeServiceImpl.class);

	@Autowired
	private AppModelTreeDao appModelTreeDao;
	
	/**
	 * 新增操作
	 */
	public int insertAppModelTree(AppModelTreeVO inAppModelTreeVo) {
		logger.debug("当前新增数据为:"+ inAppModelTreeVo.toString());
		int num = 0;
		try {
			AppModelTree appModelTree = new AppModelTree();
			beanCopy(inAppModelTreeVo, appModelTree);
			num = appModelTreeDao.insertAppModelTree(appModelTree);
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:"+ num);
		return num;
	}

	/**
	 * 删除操作
	 */
	public int deleteByPk(AppModelTreeVO inAppModelTreeVo) {
		logger.debug("当前删除数据条件为:"+ inAppModelTreeVo);
		int num = 0;
		try {
			AppModelTree appModelTree = new AppModelTree();
			beanCopy(inAppModelTreeVo, appModelTree);
			num = appModelTreeDao.deleteByPk(appModelTree);
		} catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ inAppModelTreeVo +"删除的数据条数为"+ num);
		return num;
	}


	/**
	 * 更新操作
	 */
	public int updateByPk(AppModelTreeVO inAppModelTreeVo) {
		logger.debug("当前修改数据为:"+ inAppModelTreeVo.toString());
		int num = 0;
		try {
			AppModelTree appModelTree = new AppModelTree();
			beanCopy(inAppModelTreeVo, appModelTree);
			num = appModelTreeDao.updateByPk(appModelTree);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ inAppModelTreeVo +"修改的数据条数为"+ num);
		return num;
	}
	
	/**
	 * 查询操作
	 */
	public AppModelTreeVO queryByPk(AppModelTreeVO inAppModelTreeVo) {
		
		logger.debug("当前查询参数信息为:"+ inAppModelTreeVo);
		try {
			AppModelTree queryAppModelTree = new AppModelTree();
			beanCopy(inAppModelTreeVo, queryAppModelTree);
			AppModelTree queryRslAppModelTree = appModelTreeDao.queryByPk(queryAppModelTree);
			if (Objects.nonNull(queryRslAppModelTree)) {
				AppModelTreeVO outAppModelTreeVo = beanCopy(queryRslAppModelTree, new AppModelTreeVO());
				logger.debug("当前查询结果为:"+ outAppModelTreeVo.toString());
				return outAppModelTreeVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}


	/**
	 * 查询用户权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<AppModelTreeVO> queryAllOwner(AppModelTreeVO appModelTreeVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		List<AppModelTreeVO> list = null;
		try {
			List<AppModelTree> appModelTrees = appModelTreeDao.queryAllOwnerByPage(appModelTreeVo);
			logger.debug("当前查询本人所属数据信息的结果集数量为:"+ appModelTrees.size());
			pageSet(appModelTrees, appModelTreeVo);
			list = (List<AppModelTreeVO>) beansCopy(appModelTrees, AppModelTreeVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<AppModelTreeVO> queryAllCurrOrg(AppModelTreeVO appModelTreeVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		List<AppModelTree> appModelTrees = appModelTreeDao.queryAllCurrOrgByPage(appModelTreeVo);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:"+appModelTrees.size());
		List<AppModelTreeVO> list = null;
		try {
			pageSet(appModelTrees, appModelTreeVo);
			list = (List<AppModelTreeVO>) beansCopy(appModelTrees, AppModelTreeVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<AppModelTreeVO> queryAllCurrDownOrg(AppModelTreeVO appModelTreeVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		List<AppModelTree> appModelTrees = appModelTreeDao.queryAllCurrDownOrgByPage(appModelTreeVo);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:"+ appModelTrees.size());
		List<AppModelTreeVO> list = null;
		try {
			pageSet(appModelTrees, appModelTreeVo);
			list = (List<AppModelTreeVO>) beansCopy(appModelTrees, AppModelTreeVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 批量插入应用业务模型信息记录
	 * @param appId
	 * @param appModelTreeVOs
	 * @return
	 * @throws Exception
	 */
	@Override
	public int batchInsertAppModelTrees(List<AppModelTreeVO> appModelTreeVos) {
		logger.info("批量插入应用业务模型信息记录信息......");
		if(appModelTreeVos==null || appModelTreeVos.size()==0) {
			logger.error("批量插入应用业务模型信息记录信息，待插入的数据列表为空！");
			return -1;
		}
		int count = 0;
		try {
			count = appModelTreeDao.batchInsertAppModelTrees(appModelTreeVos);
			logger.debug("批量插入应用业务模型信息记录数为：{}", count);
		} catch (Exception e) {
			logger.error("批量插入应用业务模型信息记录信息出现异常！{}", e);
			count = -1;
		}
		return count;
	}

	@Override
	public EasyUITreeData queryTreeData(AppModelTreeVO appModelTreeVo) {
		EasyUITreeData treeData = null;
		String parentId = "0";
		try {
			List<AppModelTree> dataList = appModelTreeDao.queryAllOwnerByPage(appModelTreeVo);
			if(dataList!=null && dataList.size()>0) {
				treeData = new EasyUITreeData();
				treeData.setId(parentId);
				treeData.setText("应用业务模型");
				treeData.setState("open");
				treeData.setAttributes(new HashMap<>());
				getChildrenTreeData(treeData, dataList);
			}
		} catch (Exception e) {
			logger.error("查询目录树信息出现异常！{}", e);
		}
		return treeData;
	}

	@Override
	public List<EasyUITreeData> queryTreeDataWithSingle(AppModelTreeVO appModelTreeVo) {
		try {
			List<AppModelTree> dataList = new ArrayList<>();
			if (StringUtils.isNotEmpty(appModelTreeVo.getAppModelCatalogs())) {
				String[] catalogs = StringUtils.split(appModelTreeVo.getAppModelCatalogs(), ",");
				for (String catalog : catalogs) {
					appModelTreeVo.setAppModelCatalog(catalog);
					List<AppModelTree> list = appModelTreeDao.queryAllOwnerByPage(appModelTreeVo);
					if (list != null) {
						dataList.addAll(list);
					}
				}
			} else {
				dataList = appModelTreeDao.queryAllOwnerByPage(appModelTreeVo);
			}

			return getChildrenTreeData(null, dataList);
		} catch (Exception e) {
			logger.error("查询目录树信息出现异常！{}", e);
			return Collections.emptyList();
		}
	}

	/**
	 * 获取子节点
	 * @param treeData
	 * @param dataList
	 */
	private List<EasyUITreeData> getChildrenTreeData(EasyUITreeData treeData, List<AppModelTree> dataList) {

		Map<String, EasyUITreeData> nodeMap = new HashMap<>(dataList.size());
		for (AppModelTree tree : dataList) {
			EasyUITreeData easyUITreeData = new EasyUITreeData();
			easyUITreeData.setId(tree.getPackageId());
			easyUITreeData.setText(tree.getPackageName());
			easyUITreeData.setpId(tree.getPackageAbvId());

			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("package_code", tree.getPackageCode());
			attributes.put("app_model_catalog", tree.getAppModelCatalog());
			attributes.put("pType", "page");
			easyUITreeData.setAttributes(attributes);
			nodeMap.put(easyUITreeData.getId(), easyUITreeData);
		}
		if (treeData != null) {
			nodeMap.put(treeData.getId(), treeData);
		}

		EasyUITreeData parent, child = null;
		List<EasyUITreeData> root = new ArrayList<>();
		for(AppModelTree tree : dataList) {
			parent = nodeMap.get(tree.getPackageAbvId());
			if (parent != null) {
				if (parent.getChildren() == null) {
					parent.setChildren(new ArrayList<>());
				}
				child = nodeMap.get(tree.getPackageId());
				parent.getChildren().add(child);
				parent.getAttributes().put("pType", "dir");
				parent.setState("closed");
			} else {
				child = nodeMap.get(tree.getPackageId());
				root.add(child);
			}
		}

		if (root.size() > 0) {
			root.get(0).setState("open");
		}
		return root;
	}

}
